package com.bigData.main.TestSocket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class TestServer {
    private static ServerSocket serverSocket;
    private static volatile boolean running = false;
    private static Thread serverThread;

    public static synchronized void startAsService() {
        if (running) {
            System.out.println("Server is already running");
            return;
        }

        try {
            serverSocket = new ServerSocket();
            serverSocket.bind(new InetSocketAddress("127.0.0.1", 8099)); // 使用普通Socket
            running = true;
            System.out.println("Socket服务已启动，端口：8099");

            serverThread = new Thread(() -> {
                try {
                    while (running) {
                        Socket client = serverSocket.accept();
                        new ServerThread(client).start();
                    }
                } catch (IOException e) {
                    if (!serverSocket.isClosed()) {
                        e.printStackTrace();
                    }
                }
            });
            serverThread.start();

            // 添加关闭钩子
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                try {
                    stopServer();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }));
        } catch (Exception e) {
            System.err.println("Failed to start server: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public static synchronized void stopServer() throws IOException {
        if (serverSocket != null && !serverSocket.isClosed()) {
            running = false;
            serverSocket.close();
            System.out.println("Socket服务已停止");

            if (serverThread != null) {
                serverThread.interrupt();
            }
        }
    }

    public static boolean isRunning() {
        return running;
    }
}